package material

import (
	"github.com/EDDYCJY/gsema"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-demo/app/datacenter/cron/internal/svc"
	"time"
)

type Server struct {
	svcCtx *svc.DownloadSvc
}

func NewServer(svcCtx *svc.DownloadSvc) *Server {
	return &Server{
		svcCtx: svcCtx,
	}
}

func (s *Server) Run(d int, sTime, eTime string, isToday bool, thread int, platform int) {
	var startTime, endTime string
	nowTime := time.Now()
	if isToday {
		startTime = nowTime.Format("2006-01-02")
		endTime = startTime
	} else {
		startTime = nowTime.AddDate(0, 0, -d-1).Format("2006-01-02")
		endTime = nowTime.AddDate(0, 0, -d).Format("2006-01-02")
		if len(sTime) > 0 && sTime != nowTime.Format("2006-01-02") {
			startTime = sTime
		}
		if len(eTime) > 0 && eTime != nowTime.Format("2006-01-02") {
			endTime = eTime
		}
	}

	//nowTime := time.Now()
	s.svcCtx.Logger.Info("素材下载【download】开始 ", " start: ", startTime, " end: ", endTime)

	var sema = gsema.NewSemaphore(thread)
	accountIds := []uint64{1, 3, 4, 4, 5}

	for _, id := range accountIds {
		sema.Add(1)
		go func(id uint64) {
			defer sema.Done()
			s.DoTask(id)
		}(id)
	}
	sema.Wait()

	logx.Infof("素材下载【download】完成  advs: = %v 。 time : %v 。 thread : %v ", len(accountIds), time.Since(nowTime), thread)
}

func (s *Server) DoTask(accountId uint64) {
	// 业务逻辑
	logx.Infof("accountId: %v", accountId)
}
